package com.shr.xsunmvc.route;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.shr.xsunmvc.util.PathUtils;

/**
 * 路由匹配类
 * @author sun haoran
 *
 */
public class RouteMatch {
	private List<Route> routeList ;
	
	public RouteMatch(List<Route> routeList){
		this.routeList = routeList ;
	}
	
	public void setRoute(List<Route> routeList){
		this.routeList = routeList ;
	}
	
	/**
	 * 根据 path 找到对应的路由
	 * @param path
	 */
	public Route findRoute(String path){
		String cleanPath = parsePath(path);
		List<Route> matchRoutes = new ArrayList<>() ;
		for(Route route : this.routeList){
			if(matchPath(route.getPath(), cleanPath)){
				matchRoutes.add(route) ;
			}
		}
		sortMatchRoutes(path, matchRoutes);
		
		return matchRoutes.size() > 0 ? matchRoutes.get(0) : null ;
	}


	private void sortMatchRoutes(String path, List<Route> matchRoutes) {
		Collections.sort(matchRoutes, new Comparator<Route>(){

			@Override
			public int compare(Route o1, Route o2) {
				if(o2.getPath().equals(path))
					return o2.getPath().indexOf(path);
				return -1 ;
			}
			
		});
	}

	/**
	 * ??????????
	 * @param path
	 * @param cleanPath
	 * @return
	 */
	private boolean matchPath(String path, String cleanPath) {
		path = path.replaceAll(PathUtils.VAR_REGEX, PathUtils.REPLACE) ;
		return cleanPath.matches("(?i)" + path) ; //忽略大小写模式
	}

	private String parsePath(String path) {
		path = PathUtils.fixPath(path) ;
		try {
			URI uri = new URI(path);
			return uri.getPath();
		} catch (URISyntaxException e) {
			e.printStackTrace();
			return null ;
		}
	}

}
